<template>
  <div :class="['ca-container']">
    <div class="ca-content">
      <view class="u-wrap">
        <view class="u-menu-wrap">
          <scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
                       :scroll-into-view="itemId">
            <view v-for="(item,index) in tabbar" :key="index" class="u-tab-item" :class="[current == index ? 'u-tab-item-active' : '']"
                  @tap.stop="swichMenu(index)">
              <text class="u-line-1">{{item.name}}</text>
            </view>
          </scroll-view>
          <scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box" @scroll="rightScroll">
            <view class="page-view">
              <view class="class-item" :id="'item' + index" v-for="(item , index) in tabbar" :key="index">
                <view class="item-title">
                  <text>{{item.name}}</text>
                </view>
                <view class="item-container">
                  <view class="thumb-box" v-for="(item1, index1) in item.goods" :key="index1">
                    <image class="image-cart" :src="item1.image"></image>
                    <div class="item-content">
                      <div class="item-name">{{ item1.name }}</div>
                      <div class="item-desc">{{ item1.desc }}</div>
                      <div class="item-price">
                        <div class="item-price-left">
                          <div class="item-price-unit">￥</div>
                          <div class="item-price-value">{{ isCompany ? item1.company_price :item1.price }}</div>
                        </div>
                        <div v-if="item1.spec && item1.spec.length" class="check-button" @click="openPopup(item1)">选规格</div>
                        <div v-else class="check-button check-button2">售罄</div>
                      </div>
                    </div>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <u-popup v-model="show" mode="bottom" border-radius="14">
          <div class="food-popup" style="padding-top: 40rpx">
            <div class="food-popup-item" v-for="item in foodCategoryList">
              <div class="food-popup-item-label">{{ item.name }}</div>
              <div class="food-popup-item-content">
                <div
                    @click="changeFoodCategory(item, sub.name)"
                    :class="['food-popup-item-value', item.check === sub.name ? 'active' : '']" v-for="sub in item.children">
                  {{ sub.name }}
                </div>
              </div>

            </div>
            <div style="display: flex;align-items: center;justify-content: space-between;
            border-top: 1px solid rgb(235, 235, 235);padding: 20rpx 0 10rpx 0">
              <div class="item-price-left" style="padding-left: 30rpx">
                <div class="item-price-unit">￥</div>
                <div class="item-price-value">{{ food.totalPrice }}</div>
              </div>
              <div style="display: flex;align-items: center;justify-content: flex-end;padding-right: 20px;">
                <u-icon name="minus-circle" color="#999" size="48" @click="onminus"></u-icon>
                <text style="margin: 0 20rpx;line-height: 48rpx">{{ food.count }}</text>
                <u-icon name="plus-circle-fill" color="#f15929" size="48" @click="onAdd"></u-icon>
              </div>
            </div>
            <div class="food-button">
              <div class="button" @click="show = false">取消</div>
              <div class="button button-primary" @click="onAddCart">加入购物车</div>
            </div>
          </div>
        </u-popup>
        <u-popup v-model="show2" mode="bottom" border-radius="14">
          <div class="food-popup cart-popup">
            <view class="item-container">
              <u-empty v-if="carList.length === 0" mode="car"></u-empty>
              <view class="thumb-box" v-for="(item1, index1) in carList" :key="index1">
                <image class="image-cart" :src="item1.image"></image>
                <div class="item-content">
                  <div class="item-name">{{ item1.name }}</div>
                  <div class="item-desc">{{ item1.spec_key }}</div>
                  <div class="item-price">
                    <div class="item-price-left">
                      <div class="item-price-unit">￥</div>
                      <div class="item-price-value">{{ item1.unit_price }}</div>
                    </div>
                    <div style="display: flex;align-items: center;justify-content: flex-end;padding-right: 20px;">
                      <u-icon name="minus-circle" color="#999" size="48" @click="onminusItem(item1)"></u-icon>
                      <text style="margin: 0 20rpx;line-height: 48rpx">{{ item1.count }}</text>
                      <u-icon name="plus-circle-fill" color="#f15929" size="48" @click="onAddItem(item1)"></u-icon>
                    </div>
                  </div>
                </div>
              </view>
            </view>

            <div class="food-button" v-if="carList.length">
              <div class="button button-primary" @click="onConfirm">结算</div>
            </div>
          </div>
        </u-popup>
      </view>
    </div>
    <div class="footer-car">
      <div style="flex-grow: 1;display: flex;align-items: center;position:relative;">
        <div style="position:relative;" @click="openCart">
          <u-icon name="shopping-cart" color="#ff7043" size="48">
          </u-icon>
          <u-badge class="badge" is-center :count="totalCount">
          </u-badge>
        </div>
      </div>
      <div>
        <div class="button button-primary" style="margin: 20rpx 0" @click="onConfirm">结算</div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      baseUrl: this.$baseUrl,
      keyword: '',
      scrollTop: 0, //tab标题的滚动条位置
      oldScrollTop: 0,
      current: 0, // 预设当前项的值
      menuHeight: 0, // 左边菜单的高度
      menuItemHeight: 0, // 左边菜单item的高度
      itemId: '', // 栏目右边scroll-view用于滚动的id
      tabbar: [],
      menuItemPos: [],
      arr: [],
      scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
      timer: null, // 定时器
      food: {},
      show: false,
      foodCategoryList: [
      ],
      carList: [],
      show2: false
    }
  },
  onShow() {
    this.carList = uni.getStorageSync('carList') || [];
    this.$api.categoryList().then(res => {
      this.tabbar = res.map(item => {
        return {
          ...item,
          goods: item.goods.map(sub => {
            let spec = []
            if (sub.spec) {
              spec = JSON.parse(sub.spec)
            }
            return {
              ...sub,
              spec,
              count: 0
            }
          })
        }
      });
      console.log(this.tabbar)
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
    totalCount() {
      let count = 0;
      this.carList.forEach((val) => {
        count += val.count;
      })
      return count;
    },
    isCompany() {
      return this.userInfo && this.userInfo.company_id
    }
  },
  onReady() {
    this.getMenuItemTop()
  },
  methods: {
    openCart() {
      this.show2 = true;
    },
    // 加入购物车
    onAddCart(){
      console.log('this.food',this.food)
      const item = this.food;
      let flag = false;
      this.carList.forEach((val) => {
        if(val.spec_key === item.spec_key) {
          val.count += item.count;
          flag = true;
        }
      })
      if(!flag) {
        this.carList.push({
          ...item,
        })
      }
      uni.setStorageSync('carList', this.carList)
      this.show = false;
    },
    onminusItem(item) {
      if (item.count > 0) {
        item.count--
      } else {
        this.carList.splice(this.carList.findIndex(val => val.id === item.id && val.spec_key === item.spec_key), 1)
      }
      uni.setStorageSync('carList', this.carList)
    },
    onAddItem(item) {
      item.count++
      uni.setStorageSync('carList', this.carList)
    },
    // 打开弹窗
    openPopup(item) {
      this.foodCategoryList = item.spec.map(_item => {
        return {
          ..._item,
          check: '',
          children: _item.children.map(sub => {
            return {
              ...sub,
            }
          })
        }
      })
      // 默认选中每一个规格的第一个子规格
      this.foodCategoryList.forEach(item => {
        item.check = item.children[0].name
      })
      this.food = {
        ...item,
        spec_key: '',
        spec_check: [],
        totalPrice: 0,
        count: 1
      };
      this.show = true;
      this.updateCheckFood()
    },
    updateCheckFood() {
      let checkedList = this.foodCategoryList.filter(item => item.check)
      let spec_check = []
      checkedList.forEach(item => {
        item.children.forEach(sub => {
          if (sub.name === item.check) {
            spec_check.push({
              ...sub,
              pname: item.name
            })
          }
        })
      })
      this.food.spec_key = checkedList.map(item => {
        return item.check
      }).join(',')
      // spec_check里面的价格之和 * 总数量0
      this.food.unit_price = 0
      this.food.totalPrice = spec_check.reduce((total, item) => {
        if (this.isCompany) {
          this.food.unit_price = item.company_price
          return total + Number(item.company_price || 0)
        } else {
          this.food.unit_price = item.price
          return total + Number(item.price)
        }
      }, 0) * this.food.count
      this.food.spec_check = spec_check
    },
    changeFoodCategory(item, name) {
      if (item.check === name) {
        item.check = ''
      } else {
        item.check = name;
      }
      this.updateCheckFood()
    },
    onAdd() {
      this.food.count++
      this.updateCheckFood()
    },
    onminus() {
      if(this.food.count > 1) {
        this.food.count--
        this.updateCheckFood()
      }
    },
    onConfirm() {
      console.log(this.userInfo)
      if (!this.userInfo.id) {
        // 确认对话框
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/user/login'
              })
            }
          }
        })
        return;
      }
      if(this.carList.length === 0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return ;
      }
      uni.setStorageSync('carList', [])
      uni.setStorageSync('buyList', this.carList)
      uni.navigateTo({
        url: '/pages/cart/cart'
      })
    },
    // 点击左边的栏目切换
    async swichMenu(index) {
      if(this.arr.length == 0) {
        await this.getMenuItemTop();
      }
      if (index == this.current) return;
      this.scrollRightTop = this.oldScrollTop;
      this.$nextTick(function(){
        this.scrollRightTop = this.arr[index];
        this.current = index;
        this.leftMenuStatus(index);
      })
    },
    // 获取一个目标元素的高度
    getElRect(elClass, dataVal) {
      new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.' + elClass).fields({
          size: true
        }, res => {
          // 如果节点尚未生成，res值为null，循环调用执行
          if (!res) {
            setTimeout(() => {
              this.getElRect(elClass);
            }, 10);
            return;
          }
          this[dataVal] = res.height;
          resolve();
        }).exec();
      })
    },
    // 观测元素相交状态
    async observer() {
      this.tabbar.map((val, index) => {
        let observer = uni.createIntersectionObserver(this);
        // 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
        // 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
        observer.relativeTo('.right-box', {
          top: 0
        }).observe('#item' + index, res => {
          if (res.intersectionRatio > 0) {
            let id = res.id.substring(4);
            this.leftMenuStatus(id);
          }
        })
      })
    },
    // 设置左边菜单的滚动状态
    async leftMenuStatus(index) {
      this.current = index;
      // 如果为0，意味着尚未初始化
      if (this.menuHeight == 0 || this.menuItemHeight == 0) {
        await this.getElRect('menu-scroll-view', 'menuHeight');
        await this.getElRect('u-tab-item', 'menuItemHeight');
      }
      // 将菜单活动item垂直居中
      this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
    },
    // 获取右边菜单每个item到顶部的距离
    getMenuItemTop() {
      new Promise(resolve => {
        let selectorQuery = uni.createSelectorQuery();
        selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
          // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
          if(!rects.length) {
            setTimeout(() => {
              this.getMenuItemTop();
            }, 10);
            return ;
          }
          rects.forEach((rect) => {
            // 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
            this.arr.push(rect.top - rects[0].top);
            resolve();
          })
        }).exec()
      })
    },
    // 右边菜单滚动
    async rightScroll(e) {
      this.oldScrollTop = e.detail.scrollTop;
      if(this.arr.length == 0) {
        await this.getMenuItemTop();
      }
      if(this.timer) return ;
      if(!this.menuHeight) {
        await this.getElRect('menu-scroll-view', 'menuHeight');
      }
      setTimeout(() => { // 节流
        this.timer = null;
        // scrollHeight为右边菜单垂直中点位置
        let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
        for (let i = 0; i < this.arr.length; i++) {
          let height1 = this.arr[i];
          let height2 = this.arr[i + 1];
          // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
          if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
            this.leftMenuStatus(i);
            return ;
          }
        }
      }, 10)
    }
  }
}
</script>

<style lang="scss" scoped>
.ca-container {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg,hsla(0,0%,96.9%,0),#f7f7f7,#f7f7f7),linear-gradient(180deg,#fccf00,#cbf7e9);
  .ca-content {
    flex-grow: 1;
    overflow: hidden;
  }

  .footer-car {
    width: 100%;
    height: 100rpx;
    background-color: #ffffff;
    border-top: 1px solid rgb(235, 235, 235);
    padding:0 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .badge {
      background-color: #ff7043;
      color: #ffffff;
    }
    .footer-car-button {
      flex-shrink: 0;
      height: 100%;
      width: 150px;
      line-height: 100rpx;
      background-color: #ff7043;
      color: #ffffff;
      text-align: center;
    }
  }
  .food-popup {
    padding-bottom: 20rpx;
    .food-button {
      display: flex;
      justify-content: space-between;
      padding: 0 20px 20px;

      .button {
        display: inline-block;
        line-height: 22px;
        padding: 10px 15px;
        margin: 12px 0 2px 0px;
        border-radius: 5px;
        width: 45%;
        text-align: center;
        background-color: rgba(255, 112, 67, .12549019607843137);
        border: 1px solid #ff7043;
        color: #ff7043;
      }
      .button-primary {
        background-color: #ff7043;
        color: #ffffff;
      }
    }
    .item-price-left {
      flex-grow: 1;
      display: flex;
      align-items: flex-end;
      color: rgb(223, 60, 57);
      .item-price-unit {
        padding-bottom: 8rpx;
        font-size: 20rpx;
        line-height: 20rpx;
      }
      .item-price-value {
        font-size: 32rpx;
        font-weight: bold;
      }
    }

    .food-popup-item {
      padding:16rpx 20px;
      padding-top: 0;
    }
    .food-popup-item-label {
      flex-shrink: 0;
      font-size: 14px;
      color: #666666;
      min-width: 60px;
    }
    .food-popup-item-content {
      flex-grow: 1;
      display: flex;
      flex-wrap: wrap;
    }
    .food-popup-item-value {
      display: inline-block;
      line-height: 22px;
      padding: 5px 15px;
      margin: 12px 15px 2px 0px;
      border-radius: 5px;
      min-width: 70px;
      text-align: center;
      background-color: #f5f5f5;
      border: 1px solid #f5f5f5;
      &.active {
        background-color: rgba(255, 112, 67, .12549019607843137);
        border: 1px solid #ff7043;
        color: #ff7043;
      }
    }
  }
  .cart-popup {
    background-color: #f8f7f8!important;
    padding: 20rpx;
    .item-container {
      min-height: 500rpx;
      background-color: #ffffff;
      padding: 20rpx;
      .thumb-box {
        border-bottom: 1px solid rgb(235, 235, 235);
      }
    }
    .food-button {
      .button {
        width: 100%;
      }
    }
  }
  .u-wrap {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .u-search-box {
    padding: 18rpx 30rpx;
  }

  .u-menu-wrap {
    flex: 1;
    display: flex;
    overflow: hidden;
  }

  .u-search-inner {
    background-color: rgb(234, 234, 234);
    border-radius: 100rpx;
    display: flex;
    align-items: center;
    padding: 10rpx 16rpx;
  }

  .u-search-text {
    font-size: 26rpx;
    color: $u-tips-color;
    margin-left: 10rpx;
  }

  .u-tab-view {
    width: 200rpx;
    height: 100%;
  }

  .u-tab-item {
    height: 110rpx;
    background: #f6f6f6;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    color: #444;
    font-weight: 400;
    line-height: 1;
  }

  .u-tab-item-active {
    position: relative;
    color: #000;
    font-size: 30rpx;
    font-weight: 600;
    background: #fff;
  }

  .u-tab-item-active::before {
    content: "";
    position: absolute;
    border-left: 4px solid #f15929;
    height: 32rpx;
    left: 0;
    top: 39rpx;
  }

  .u-tab-view {
    height: 100%;
  }

  .right-box {
    background-color: rgb(250, 250, 250);
  }

  .page-view {
    padding: 16rpx;
  }

  .class-item {
    margin-bottom: 30rpx;
    background-color: #fff;
    padding: 16rpx;
    border-radius: 8rpx;
  }

  .class-item:last-child {
    min-height: 100vh;
  }

  .item-title {
    font-size: 26rpx;
    color: $u-main-color;
    font-weight: bold;
  }

  .item-menu-name {
    font-weight: normal;
    font-size: 24rpx;
    color: $u-main-color;
  }

  .item-container {
    position: relative;
  }

  .thumb-box {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 20rpx 0;
  }

  .image-cart {
    flex-shrink: 0;
    width: 120rpx;
    height: 120rpx;
  }
  .item-content {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .item-name {
      font-size: 28rpx;
      color: #080808;
    }
    .item-desc {
      color: #aaa!important;
      font-size: 24rpx;
      padding-top: 10rpx;
    }
    .check-button {
      display: inline-block;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      background-color: #f15929;
      color: #fff;
      font-size: 24rpx;
    }
    .check-button2 {
      display: inline-block;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      background-color: #ccc;
      color: #fff;
      font-size: 24rpx;
    }
    .item-price {
      display: flex;
      align-items: center;
      padding-top: 5rpx;
      width: 100%;
      justify-content: space-between;
      .item-price-left {
        flex-grow: 1;
        display: flex;
        align-items: flex-end;
        color: rgb(223, 60, 57);
        .item-price-unit {
          padding-bottom: 8rpx;
          font-size: 20rpx;
          line-height: 20rpx;
        }
        .item-price-value {
          font-size: 32rpx;
          font-weight: bold;
        }
      }
    }
  }
}

</style>
